package com.dianrui.firemenmonitor.activity;

import android.graphics.Point;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.dianrui.firemenmonitor.Constant;
import com.dianrui.firemenmonitor.R;
import com.dianrui.firemenmonitor.adapter.TrackAdapter;
import com.dianrui.firemenmonitor.bean.Track;
import com.dianrui.firemenmonitor.util.BaiduUtils;
import com.dianrui.firemenmonitor.util.OkHttpUtils;
import com.dianrui.firemenmonitor.util.StringUtils;
import com.dianrui.firemenmonitor.util.Url;
import com.dianrui.firemenmonitor.view.TrackChooseDatePicker;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TrackDetailsActivity extends BaseActivity {

    private BaiduMap baiduMap;
    private List<Track> trackList = new ArrayList<>();
    private TrackAdapter trackAdapter;
    List<LatLng> gps = new ArrayList<>();

    @BindView(R.id.right_img)
    ImageView rightImg;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.map)
    MapView map;
    @BindView(R.id.track_listview)
    ListView listview;
    @BindView(R.id.emptyView)
    LinearLayout emptyView;



    @Override
    public int getContentViewId() {
        return R.layout.activity_track_details;
    }

    @Override
    public void initView() {
        customInit(R.color.blue_518bfa);
        title.setText(getString(R.string.attendance_track));
        baiduMap = map.getMap();//获取百度地图的实例
        BaiduUtils.initUI(map);
        rightImg.setVisibility(View.VISIBLE);
        rightImg.setImageResource(R.mipmap.track_caldaner);
        trackAdapter = new TrackAdapter(TrackDetailsActivity.this, trackList);
        listview.setAdapter(trackAdapter);
        baiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                getTrack();
            }
        });
        map.getChildAt(0).setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {

                } else {

                }
                return false;
            }
        });


    }


    private void getTrack() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("inputtime", simpleDateFormat.format(date));
        OkHttpUtils.getInstance().postWithMemberToken(Url.TRACK, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {
                                if (trackList != null) {
                                    trackList.clear();
                                }
                                if (gps != null) {
                                    gps.clear();
                                }
                                JSONArray data = jsonObject.optJSONArray("data");
                                if (data.length() > 0) {
                                    for (int i = 0; i < data.length(); i++) {
                                        Track track = new Track();
                                        JSONObject jsonObject2 = data.optJSONObject(i);
                                        track.Id = jsonObject2.optString("Id");
                                        track.latitude = jsonObject2.optDouble("latitude");
                                        track.inputtime = jsonObject2.optString("inputtime");
                                        track.address = jsonObject2.optString("address");
                                        track.lat = jsonObject2.optString("latitude").split(",")[1];
                                        track.lng = jsonObject2.optString("latitude").split(",")[0];
                                        trackList.add(track);
                                    }
                                    if (trackAdapter != null) {
                                        trackAdapter.refresh(trackList);
                                    }

                                    final LatLng current = new LatLng(Double.valueOf(trackList.get(trackList.size() - 1).lat), Double.valueOf(trackList.get(trackList.size() - 1).lng));
                                    MapStatus mapStatus = new MapStatus.Builder().target(current).zoom(16).build();
                                    MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
                                    map.getMap().setMapStatus(mapStatusUpdate);
                                    for (int i = 0; i < trackList.size(); i++) {
                                        gps.add(new LatLng(Double.valueOf(trackList.get(i).lat), Double.valueOf(trackList.get(i).lng)));
                                    }
                                    if (trackList.size() > 1) {
                                        MarkerOptions markerOptions = new MarkerOptions();
                                        Bundle bundle = new Bundle();
                                        bundle.putInt("type", 1);//先把上个界面用bundle存起来以及存下type，方便区别起点和终点
                                        bundle.putString("start", trackList.get(0).address);
                                        markerOptions.position(new LatLng(Double.valueOf(trackList.get(0).lat), Double.valueOf(trackList.get(0).lng))).icon(BitmapDescriptorFactory.fromView(LayoutInflater.from(TrackDetailsActivity.this).inflate(R.layout.start_point, null))).extraInfo(bundle).zIndex(99);
                                        baiduMap.addOverlay(markerOptions);


                                        MarkerOptions markerOptions1 = new MarkerOptions();
                                        Bundle bundle1 = new Bundle();
                                        bundle1.putInt("type", 2);//先把上个界面用bundle存起来以及存下type，方便区别起点和终点
                                        bundle1.putString("end", trackList.get(trackList.size() - 1).address);
                                        markerOptions1.position(new LatLng(Double.valueOf(trackList.get(trackList.size() - 1).lat), Double.valueOf(trackList.get(trackList.size() - 1).lng))).icon(BitmapDescriptorFactory.fromView(LayoutInflater.from(TrackDetailsActivity.this).inflate(R.layout.end_point, null))).extraInfo(bundle1).zIndex(100);
                                        baiduMap.addOverlay(markerOptions1);
                                    }
                                    baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

                                        @Override
                                        public boolean onMarkerClick(Marker marker) {
                                            if (marker.getExtraInfo() != null) {
                                                switch (marker.getExtraInfo().getInt("type")) {
                                                    case 1:
                                                        String startPaths = marker.getExtraInfo().getString("start");
                                                        View view = LayoutInflater.from(TrackDetailsActivity.this).inflate(R.layout.start_point_bubble, null);
                                                        TextView startTxt = view.findViewById(R.id.start_point_text);
                                                        startTxt.setText(startPaths);
                                                        final LatLng ll = marker.getPosition();
                                                        Point p = baiduMap.getProjection().toScreenLocation(ll);
                                                        LatLng llInfo = baiduMap.getProjection().fromScreenLocation(p);
                                                        InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(view), llInfo, -47, new InfoWindow.OnInfoWindowClickListener() {
                                                            @Override
                                                            public void onInfoWindowClick() {
                                                                baiduMap.hideInfoWindow();
                                                            }
                                                        });
                                                        baiduMap.showInfoWindow(mInfoWindow);
                                                        break;
                                                    case 2:
                                                        String endPath = marker.getExtraInfo().getString("end");
                                                        View view1 = LayoutInflater.from(TrackDetailsActivity.this).inflate(R.layout.end_point_bubble, null);
                                                        TextView endTxt = view1.findViewById(R.id.end_point_text);
                                                        endTxt.setText(endPath);
                                                        final LatLng ll1 = marker.getPosition();
                                                        Point p1 = baiduMap.getProjection().toScreenLocation(ll1);
                                                        LatLng llInfo1 = baiduMap.getProjection().fromScreenLocation(p1);
                                                        InfoWindow mInfoWindow1 = new InfoWindow(BitmapDescriptorFactory.fromView(view1), llInfo1, -47, new InfoWindow.OnInfoWindowClickListener() {
                                                            @Override
                                                            public void onInfoWindowClick() {
                                                                baiduMap.hideInfoWindow();
                                                            }
                                                        });
                                                        baiduMap.showInfoWindow(mInfoWindow1);
                                                        break;
                                                    default:
                                                        break;
                                                }
                                            }
                                            return true;
                                        }
                                    });


                                    if (gps.size() > 1) {
                                        BaiduUtils.drawliness(map, gps);
                                    }

                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (trackList.size()<=0) {
                        emptyView.setVisibility(View.VISIBLE);
                        listview.setVisibility(View.GONE);
                    }else {
                        emptyView.setVisibility(View.GONE);
                        listview.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
    }


    private void getDateTrack(String datetime) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("inputtime", datetime);
        OkHttpUtils.getInstance().postWithMemberToken(Url.TRACK, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {
                                if (trackList != null) {
                                    trackList.clear();
                                }
                                if (gps != null) {
                                    gps.clear();
                                }
                                JSONArray data = jsonObject.optJSONArray("data");
                                if (data.length() > 0) {
                                    for (int i = 0; i < data.length(); i++) {
                                        Track track = new Track();
                                        JSONObject jsonObject2 = data.optJSONObject(i);
                                        track.Id = jsonObject2.optString("Id");
                                        track.latitude = jsonObject2.optDouble("latitude");
                                        track.inputtime = jsonObject2.optString("inputtime");
                                        track.address = jsonObject2.optString("address");
                                        track.lat = jsonObject2.optString("latitude").split(",")[1];
                                        track.lng = jsonObject2.optString("latitude").split(",")[0];
                                        trackList.add(track);
                                    }
                                    if (trackAdapter != null) {
                                        trackAdapter.refresh(trackList);
                                    }

                                    final LatLng current = new LatLng(Double.valueOf(trackList.get(trackList.size() - 1).lat), Double.valueOf(trackList.get(trackList.size() - 1).lng));
                                    MapStatus mapStatus = new MapStatus.Builder().target(current).zoom(16).build();
                                    MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
                                    map.getMap().setMapStatus(mapStatusUpdate);
                                    for (int i = 0; i < trackList.size(); i++) {
                                        gps.add(new LatLng(Double.valueOf(trackList.get(i).lat), Double.valueOf(trackList.get(i).lng)));
                                    }
                                    if (trackList.size() > 1) {
                                        MarkerOptions markerOptions = new MarkerOptions();
                                        Bundle bundle = new Bundle();
                                        bundle.putInt("type", 1);//先把上个界面用bundle存起来以及存下type，方便区别起点和终点
                                        bundle.putString("start", trackList.get(0).address);
                                        markerOptions.position(new LatLng(Double.valueOf(trackList.get(0).lat), Double.valueOf(trackList.get(0).lng))).icon(BitmapDescriptorFactory.fromView(LayoutInflater.from(TrackDetailsActivity.this).inflate(R.layout.start_point, null))).extraInfo(bundle).zIndex(99);
                                        baiduMap.addOverlay(markerOptions);


                                        MarkerOptions markerOptions1 = new MarkerOptions();
                                        Bundle bundle1 = new Bundle();
                                        bundle1.putInt("type", 2);//先把上个界面用bundle存起来以及存下type，方便区别起点和终点
                                        bundle1.putString("end", trackList.get(trackList.size() - 1).address);
                                        markerOptions1.position(new LatLng(Double.valueOf(trackList.get(trackList.size() - 1).lat), Double.valueOf(trackList.get(trackList.size() - 1).lng))).icon(BitmapDescriptorFactory.fromView(LayoutInflater.from(TrackDetailsActivity.this).inflate(R.layout.end_point, null))).extraInfo(bundle1).zIndex(100);
                                        baiduMap.addOverlay(markerOptions1);
                                    }
                                    baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

                                        @Override
                                        public boolean onMarkerClick(Marker marker) {
                                            if (marker.getExtraInfo() != null) {
                                                switch (marker.getExtraInfo().getInt("type")) {
                                                    case 1:
                                                        String startPaths = marker.getExtraInfo().getString("start");
                                                        View view = LayoutInflater.from(TrackDetailsActivity.this).inflate(R.layout.start_point_bubble, null);
                                                        TextView startTxt = view.findViewById(R.id.start_point_text);
                                                        startTxt.setText(startPaths);
                                                        final LatLng ll = marker.getPosition();
                                                        Point p = baiduMap.getProjection().toScreenLocation(ll);
                                                        LatLng llInfo = baiduMap.getProjection().fromScreenLocation(p);
                                                        InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(view), llInfo, -47, new InfoWindow.OnInfoWindowClickListener() {
                                                            @Override
                                                            public void onInfoWindowClick() {
                                                                baiduMap.hideInfoWindow();
                                                            }
                                                        });
                                                        baiduMap.showInfoWindow(mInfoWindow);
                                                        break;
                                                    case 2:
                                                        String endPath = marker.getExtraInfo().getString("end");
                                                        View view1 = LayoutInflater.from(TrackDetailsActivity.this).inflate(R.layout.end_point_bubble, null);
                                                        TextView endTxt = view1.findViewById(R.id.end_point_text);
                                                        endTxt.setText(endPath);
                                                        final LatLng ll1 = marker.getPosition();
                                                        Point p1 = baiduMap.getProjection().toScreenLocation(ll1);
                                                        LatLng llInfo1 = baiduMap.getProjection().fromScreenLocation(p1);
                                                        InfoWindow mInfoWindow1 = new InfoWindow(BitmapDescriptorFactory.fromView(view1), llInfo1, -47, new InfoWindow.OnInfoWindowClickListener() {
                                                            @Override
                                                            public void onInfoWindowClick() {
                                                                baiduMap.hideInfoWindow();
                                                            }
                                                        });
                                                        baiduMap.showInfoWindow(mInfoWindow1);
                                                        break;
                                                    default:
                                                        break;
                                                }
                                            }
                                            return true;
                                        }
                                    });


                                    if (gps.size() > 1) {
                                        BaiduUtils.drawliness(map, gps);
                                    }

                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (trackList.size()<=0) {
                        emptyView.setVisibility(View.VISIBLE);
                        listview.setVisibility(View.GONE);
                    }else {
                        emptyView.setVisibility(View.GONE);
                        listview.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map.onSaveInstanceState(outState);

    }

    @Override
    protected void onResume() {
        super.onResume();
        map.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        map.onPause();
    }


    @OnClick({R.id.back, R.id.right_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.right_img:
                TrackChooseDatePicker trackChooseDatePicker = new TrackChooseDatePicker(this);
                trackChooseDatePicker.setDateListener(new TrackChooseDatePicker.OnDateCListener() {
                    @Override
                    public void onDateSelected(String year, String month, String day) {
                        String times = year + "-" + month + "-" + day;
                        getDateTrack(times);
                    }
                });
                trackChooseDatePicker.show();

                break;
            default:
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        map.onDestroy();
    }

}
